package com.mayn.jst.erp.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.mayn.jst.login.TaobaoLoginAction;
import com.mayn.jst.shop.action.ShopAccountAction;
import com.mayn.util.DateUtil;
import com.mayn.util.FetchUtils;
import com.mayn.util.HttpUtil;
import com.mayn.util.SendCloudMailUtil;
import com.mayn.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 生意参谋单品服务分析抓取类
 * @author 梁志渊
 * @version 
 * 版本号：【100-000-000】<br/>
 * 创建日期：:2017年7月4日 <br/>
 * 历史修订：<br/>
 */
public class SycmDarAction {

	private static final Logger LOG = LoggerFactory.getLogger(SycmDarAction.class);
	//单品服务分析-商品评分分析
	public static void dsr(Date currTime) throws Exception {
		// 获取店铺cookie
		int shopId = 5;
		String date = DateUtil.dateFmtToString(currTime,"yyyy-MM-dd");

//		JfinalInit.InitDb(false, null);

		if (TaobaoLoginAction.checkAndSaveTaobaoLoginCookie(shopId)) {
			
			String cookie = ShopAccountAction.getShopAccountCookie(shopId);
			// 获取token
			String token = TaobaoLoginAction.getSycmToken(cookie);
			LOG.info("token:" + token);
			// 获取数据
			
			LOG.info("当前抓取时间day--->"+date);
			
			List<Record> itemId_list = QueryId();
			for (int i = 0; i < itemId_list.size(); i++) {
				String itemId = itemId_list.get(i).getStr("SP_ITEM_ID");
				//LOG.info("itemId--->"+itemId);
			JSONObject json = null;
			JSONArray jsonArray = null;
			String objectStr = getItemDsrAnalysisReviewByDay(cookie, token, date, itemId).toString();
			
			if(StringUtil.isBlank(objectStr) ||  (!objectStr.contains("data") )){
				LOG.info("返回的json字符串不合法！");
				continue;
			}else {
				json = JSONObject.fromObject(objectStr);
			}
			if(StringUtil.isBlank(json) ){
				LOG.info("json为空！");
				continue;
			}
			//LOG.info(json.getString("data"));
			List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
			jsonArray = json.getJSONArray("data");
			listmap = FetchUtils.InsertToMap(jsonArray);
			

				// 判断数据库是否有数据
				if (checkDSRData(date,itemId) == true) {
					LOG.info("今天数据已采集! ");
					continue;
				}else{
					// save操作  插入数据
				if (FetchUtils.savedata_dar(listmap, itemId, date) != true) {
					LOG.info("插入失败！");
					return;
				} else {
						LOG.info("插入成功！");
					}
				}
			}
		}else{
			LOG.info("获取店铺cookie失败！");
			String mailText = "获取店铺cookie失败！"+"\r\n";
		    SendCloudMailUtil.sendMailCode(mailText,"service@mayn.com.cn");
		}
	}
	
	/**
	 * @param currTime 抓取时间
	 * 单品服务分析-重点服务指标总览
	 **/
	public static void dsr_dar(Date currTime) {

		// 获取店铺cookie
		int shopId = 5;
		String date = DateUtil.dateFmtToString(currTime,"yyyy-MM-dd");

//		JfinalInit.InitDb(false, null);
		try {
			if (TaobaoLoginAction.checkAndSaveTaobaoLoginCookie(shopId)) {

				String cookie = ShopAccountAction.getShopAccountCookie(shopId);
				// 获取token
				String token = TaobaoLoginAction.getSycmToken(cookie);
				LOG.info("token:" + token);
				// 获取数据
					LOG.info("当前抓取时间day--->"+date);
				
				// 遍历shop_product表取产品id
				List<Record> itemId_list = QueryId();
				for (int i = 0; i < itemId_list.size(); i++) {
					String itemId = itemId_list.get(i).getStr("SP_ITEM_ID");
					Map<String, Object> map = new HashMap<String, Object>();

					JSONObject json = new JSONObject();
					JSONObject Jkson = new JSONObject();
					JSONObject jsonObject = new JSONObject();
					String jsonStr = getItemDARByDay(cookie, token, date, itemId).toString() ;
//					String jsonStr = "{\"traceId\":\"0b802ac015004550365546722e441d\",\"message\":\"操作成功\",\"data\":{},\"code\":0} ";
					if(StringUtil.isBlank(jsonStr) ){
						LOG.info("返回的json字符串不合法！");
						continue;
					} 
					
					if( jsonStr.contains("data")){
						Jkson = JSONObject.fromObject(jsonStr);
					}else {
						LOG.error("jsonStr不存在data数据!");
						continue;
					}
					LOG.info(Jkson.getString("data"));
					if( Jkson.getString("data").equals("{}") || StringUtil.isBlank(Jkson.getString("data"))){
						LOG.error("data数据为空！");	
						continue;
					}
					jsonObject = JSONObject.fromObject(Jkson.getJSONObject("data"));
					if( StringUtil.isBlank(jsonObject)){
						LOG.error("jsonObject为空");
						continue;
					}
					
					//品质退款率
					json = (JSONObject) JSONObject.fromObject(jsonObject).get("rfdSucQaRate");
					LOG.info("rfdSucQaRate-->"+json.getString("value"));
					LOG.info("rfdSucQaRate_rate-->"+json.getString("rivalAvg"));
					if(StringUtil.isBlank(json.getString("value").toString())|| json.getString("value").equals("null")){
						map.put("rfdSucQaRate", 0.0);
					}else{
						map.put("rfdSucQaRate", json.get("value"));
					}
					//同比
					if(StringUtil.isBlank(json.getString("rivalAvg").toString())|| json.getString("rivalAvg").equals("null")){
						map.put("rfdSucQaRate_rate", 0.0);
					}else{
						map.put("rfdSucQaRate_rate", json.get("rivalAvg"));
					}
					//退款率
					json = (JSONObject) JSONObject.fromObject(jsonObject).get("rfdSucRate");
					LOG.info("rfdSucRate-->"+json.getString("value"));
					LOG.info("rfdSucRate_rate-->"+json.getString("rivalAvg"));
					if(StringUtil.isBlank(json.getString("value")) || json.getString("value").equals("null")){
						map.put("rfdSucRate", 0.0);
					}else{
						map.put("rfdSucRate", json.get("value"));
					}
					//同比
					if(StringUtil.isBlank(json.getString("rivalAvg").toString())|| json.getString("rivalAvg").equals("null")){
						map.put("rfdSucRate_rate", 0.0);
					}else{
						map.put("rfdSucRate_rate", json.get("rivalAvg"));
					}
					//描述相符
					json = (JSONObject) JSONObject.fromObject(jsonObject).get("descScore");
					LOG.info("descScore-->"+json.getString("value"));
					LOG.info("descScore_rate-->"+json.getString("rivalAvg"));
					if(StringUtil.isBlank(json.getString("value")) || json.getString("value").equals("null")){
						map.put("descScore", 0.0);
					}else{
						map.put("descScore", json.get("value"));
					}
					//同比
					if(StringUtil.isBlank(json.getString("rivalAvg").toString())|| json.getString("rivalAvg").equals("null")){
						map.put("descScore_rate", 0.0);
					}else{
						map.put("descScore_rate", json.get("rivalAvg"));
					}
					

					// 判断数据库是否有数据
					if (checkDARData(date,itemId) == true) {
						LOG.info("单号:"+itemId+"日期："+date+"今天数据已采集!");
		 				continue;
					}

					// save操作 插入数据
					if (FetchUtils.savedata_guide(map, itemId, date) != true) {
						LOG.info("插入失败！");
						return;
					} else {
						LOG.info("插入成功！");
					}
				}//end For
				}
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		
	
	
	/**
	 * 查询订单号
	 * @return
	 */
	private static List<Record> QueryId() {
		String sql = "select SP_ITEM_ID from shop_product  WHERE SP_DEL = 0";
		List<Record> ProductIdList = Db.find(sql);
		if(ProductIdList.size() >=1){
			return ProductIdList;
		}
		
		return null;
	}

	/**
	 * 检查单品分析表
	 * @param date 抓取时间
	 * @return
	 */
	public static boolean checkDSRData(String date,String id) {
		String sql = "select COUNT(*) from dsranalysisreview dar where dar.DAR_START_DATE =? AND dar.DAR_ITEM_ID = ?;";
		long count = 0;
			try {
				count = Db.use("erp").queryLong(sql,date,id);
			if (count >= 1){
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 检查服务指标总览表
	 * @param date 抓取时间
	 * @return
	 */
	private static boolean checkDARData(String date,String id) {
		String sql = "select COUNT(*) from dar_guide dargd where dargd.DAR_GUIDE_DATE =? AND dargd.DAR_GUIDE_ITEM_ID = ?;";
		long count = 0;
		try{
			count = Db.use("erp").queryLong(sql,date,id);
			if (count >= 1){
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 单品服务分析指定日期，指定宝贝ID数据获取
	 * @param cookie
	 * @param token
	 * @param date
	 * @param itemId
	 * @return
	 */
	public static JSONObject getItemDsrAnalysisReviewByDay(String cookie,String token,String date,String itemId){
		try{
			String url = "https://sycm.taobao.com/qos/review/item/getItemDsrAnalysisReview.json";
			
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("accept", "*/*");
			headers.put("accept-encoding", "gzip, deflate, sdch, br");
			headers.put("accept-language", "zh-CN,zh;q=0.8");
			headers.put("cache-control", "no-cache");
			headers.put("cookie", cookie);
			headers.put("pragma", "no-cache");
			headers.put("referer", "https://sycm.taobao.com/qos/item/after_sales?dateRange=" + date + "%7C" + date + "&dateType=day&itemId=" + itemId);
			headers.put("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("dateRange", date + "|" + date);
			params.put("dateType", "day");
			params.put("itemId", itemId);
			//时间戳
			long t = DateUtil.getUnixTime();
			params.put("_", String.valueOf(t));
			params.put("token", token);
			
			String resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
			if (resp.startsWith("{")) {
				JSONObject object = JSONObject.fromObject(resp);
				//判断返回数据是否合法
				if (object.containsKey("data") && object.getJSONArray("data").size()>0) {
					return object;
				}else{
					LOG.info("返回数据错误:" + resp);
					return object;
				}
			}
		}catch(Exception e){
			LOG.error("未知错误:" + e.getMessage());
		}
		return new JSONObject();
	}
	
	/**
	 * 获取重点服务指标
	 */
	public static JSONObject getItemDARByDay(String cookie,String token,String date,String itemId) {
	try{
		String url = "https://sycm.taobao.com/qos/aftersales/item/guide.json";
		
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("accept", "*/*");
		headers.put("accept-encoding", "gzip, deflate, sdch, br");
		headers.put("accept-language", "zh-CN,zh;q=0.8");
		headers.put("cache-control", "no-cache");
		headers.put("cookie", cookie);
		headers.put("pragma", "no-cache");
		headers.put("referer", "https://sycm.taobao.com/qos/item/after_sales?dateRange=" + date + "%7C" + date + "&dateType=recent1&itemId=" + itemId);
		LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
		params.put("dateRange", date + "|" + date);
		params.put("dateType", "day");
		params.put("itemId", itemId);
		//时间戳
		long t = DateUtil.getUnixTime();
		params.put("_", String.valueOf(t));
		params.put("token", token);
		
		String resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
		if (resp.startsWith("{")) {
			JSONObject object = JSONObject.fromObject(resp);
			//判断返回数据是否合法
			if (object.containsKey("data") && object.getJSONObject("data").size()>0) {
				return object;
			}else{
				LOG.error("返回数据错误:" + resp);
				return new JSONObject();
			}
		}
	}catch(Exception e){
		LOG.error("未知错误:" + e.getMessage());
	}
	return new JSONObject();
}

}
